import React, { Key, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom';
import { Button, Form, Input, Table, Card, message, Tooltip } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { hospitalSetRequest, deleteformIdRequest, piLiangDeleteIdRequest } from '../../../api/hospital/hospitalSet'
import type { getHosSetListRecordsType, getHosSetListItemsType } from '../../../api/hospital/model/hositalSet'
import style from './index.module.css'

export default function HospitalSet() {
  //编程式路由导航
  const Navigate = useNavigate()
  //定义初始值
  const [hospitalSet, setHospitalSet] = useState<getHosSetListRecordsType>([])
  //页码的初始值
  const [current, setCurrent] = useState(1)
  //total总数量
  const [total, setTotal] = useState(0)
  //pageSize每页的数量
  const [pageSize, setPageSize] = useState(3)
  //isLoading
  const [isLoading, setIsLoading] = useState(false)
  //查询表单数据初始值
  const [hosSetFormValue, setHosSetFormValue] = useState<hosSetFormvalue>({})
  //定义一个状态用来监听删除页面刷新
  const [isDelete, setIsdelete] = useState(true)
  //定义一个初始值用来改变批量删除按钮状态
  const [isSelect, setIsSelect] = useState(true)
  //定义id数组初始值
  const [ids, setIds] = useState<Key[]>([])
  //初始化前请求医院设置
  //当组件加载的时候,开始请求分页列表的数据
  //注意:异步函数不能作为useEffect的参数,因为useEffect可能会书写return一个函数起到清理作用,如果是异步函数,则return就是异步的了
  useEffect(() => {
    //请求前修改isLoading
    setIsLoading(true)
    const getHosSetList = async () => {
      const result = await hospitalSetRequest({
        page: current,
        limit: pageSize,
        ...hosSetFormValue
      })
      //console.log(result);
      setHospitalSet(result.records)
      setTotal(result.total)
      //请求结束后修改isloading
      setIsLoading(false)
    }
    getHosSetList()
  }, [current, pageSize, hosSetFormValue, isDelete, isSelect]) //监听 当数组中的值有变化的时候则执行


  //colums是控制表格的字段有哪些,title属性就是当前的字段名称,dataIndex就是用来和将来的数据进行一一对应的
  const columns = [
    {
      title: '序号',
      width: 60,
      // dataIndex: 'name',
      render(_: any, __: any, index: any) {
        return index + 1
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',

    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',
    },
    {
      title: 'api基础路径',
      dataIndex: 'apiUrl',
    },
    {
      title: '签名',
      dataIndex: 'signKey',
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName',
    },
    {
      title: '联系人手机',
      dataIndex: 'contactsPhone',
    },
    {
      title: '操作',
      // dataIndex: 'name',
      fixed: 'right' as 'right',
      width: 120,
      //获取到当前id
      render(_: any, data: getHosSetListItemsType) {
        const { id } = data
        return (
          <div>
            {/* 修改                                                    路由跳转并传值                            */}
            <Tooltip title='修改医院'>
              <Button type='primary' onClick={() => Navigate(`/syt/hospital/hospitalset/upDataSet/${id}`)} icon={<EditOutlined />} className={style.mr}></Button>
            </Tooltip>
            {/* 删除 */}
            <Tooltip title='删除医院'>
              <Button type='primary'
                danger icon={<DeleteOutlined />}
                // 删除
                onClick={deleteIdHandle(id)}
              ></Button>
            </Tooltip>
          </div >
        )
      }
    }
  ];
  //医院设置改变页码封装函数
  const hosSetChangeHandle = (current: number, pageSize: number) => {
    setCurrent(current)
    setPageSize(pageSize)
  }
  //定义表单数据类型接口
  interface hosSetFormvalue {
    hosname?: string,
    hoscode?: string
  }
  //获取表单数据函数
  const hosSetFormvalue = (value: hosSetFormvalue) => {
    //打印台结果为一个对象 对象里就是表单的值
    //设置至state
    setHosSetFormValue(value)
  }
  //路由跳转至添加医院
  const jumpAddorUpdata = () => {
    Navigate('/syt/hospital/hospitalset/addSet')
  }

  //id删除 事件函数
  const deleteIdHandle = (id: number) => {
    //调用api函数
    return async () => {
      await deleteformIdRequest(id)
      //提示信息
      message.info('删除医院成功')
      //修改状态
      setIsdelete(!isDelete)
    }
  }

  //批量删除医院 事件函数
  const batchRemoveHandle = async () => {
    await piLiangDeleteIdRequest(ids)
    //批量删除完提示
    message.info('批量删除医院成功')
    //改变批量删除的状态为禁用
    setIsSelect(true)
  }
  return (
    <div className={style.outer}>
      <Card>
        <Form
          name="basic"
          wrapperCol={{ span: 30 }}
          layout='inline'
          onFinish={hosSetFormvalue}
          autoComplete='off'
        >
          <Form.Item
            name="hosname"
          >
            <Input placeholder="医院名称" />
          </Form.Item>
          <Form.Item
            name="hoscode"
          >
            <Input placeholder='医院编号' />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>
        <div className={style.mt}>
          <Button type='primary' className={style.mr} onClick={jumpAddorUpdata}>添加</Button>
          <Button type="primary" danger disabled={isSelect} onClick={batchRemoveHandle} >批量删除</Button>
        </div>
        <Table
          className={style.outer}
          columns={columns}
          dataSource={hospitalSet}
          rowKey='id'
          //滚动条
          scroll={{ x: 1500 }}
          bordered
          loading={isLoading}
          //?
          rowSelection={{
            onChange(ids: Key[]) {
              //判断id 如果id有长度 取反 批量删除状态框改变可以用
              setIsSelect(!ids.length)
              //保存在state中
              setIds(ids)
            }
          }}
          pagination={{
            //页码的配置：当前页码
            current,
            //总数据的数量
            total,
            //每页条数
            pageSize,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 10, 20],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `总共有${total}条数据`
            },
            //页码事件
            onChange: hosSetChangeHandle
          }}
        />
      </Card>
    </div>
  )
}
